package com.frejoys.common.config;

import com.frejoys.common.filter.RepeatedlyReadFilter;
import com.frejoys.common.interceptor.AuthorityInterceptor;
import com.frejoys.common.interceptor.GlobalizationInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

    private final GlobalizationInterceptor globalizationInterceptor;

    private final AuthorityInterceptor authorityInterceptor;

    // 添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(globalizationInterceptor);
        registry.addInterceptor(authorityInterceptor);
    }

    // 开启跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // WebMvcConfigurer.super.addCorsMappings(registry);
        registry.addMapping("/**") // 设置允许跨域的路由，都允许
                .allowedOriginPatterns("*") // 设置允许跨域请求的域名
                .allowCredentials(true) // 是否支持跨域用户凭证
                .allowedMethods("GET", "POST") // 当前站点支持的跨域请求类型
                .maxAge(3600); // 超时时长设置为1小时。 时间单位是秒
    }

    /**
     * 设置自定义过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean repeatedlyReadFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        RepeatedlyReadFilter readFilter = new RepeatedlyReadFilter();
        registrationBean.setFilter(readFilter); // 设置过滤器
        registrationBean.addUrlPatterns("/*"); // 过滤所有资源
        return registrationBean;
    }

}
